package com.qili.controller;

import cn.hutool.core.util.IdUtil;
import com.qili.base.controller.BaseController;
import com.qili.base.service.BasePathConfigService;
import com.qili.core.utils.DictTypes;
import com.qili.core.utils.DictUtil;
import com.qili.core.utils.FileUtils;
import com.qili.entity.base.*;
import com.qili.entity.base.dto.BaseStageMileDTO;
import com.qili.entity.jc.*;
import com.qili.entity.jc.dto.JcProjectDTO;
import com.qili.entity.jc.dto.JcProjectMilepostDTO;
import com.qili.entity.jc.dto.JcProjectPayDTO;
import com.qili.entity.jc.dto.JcProjectStageDTO;
import com.qili.entity.supervisor.*;
import com.qili.entity.supervisor.dto.ProjectLeaderDTO;
import com.qili.entity.supervisor.dto.ProjectUnitConstructionDTO;
import com.qili.entity.supplier.ProjectPlace;
import com.qili.entity.supplier.SupplierProject;
import com.qili.entity.supplier.SupplierProjectAccept;
import com.qili.entity.supplier.dto.ProjectPlaceDTO;
import com.qili.entity.sys.SysRegion;
import com.qili.entity.sys.SysUser;
import com.qili.entity.sys.SysUserWorkExperience;
import com.qili.entity.sys.dto.SysUserDTO;
import com.qili.entity.zx.ZxProjectMilepost;
import com.qili.service.SysUserService;
import com.qili.service.base.*;
import com.qili.service.jc.*;
import com.qili.service.jc.JcProjectMilepostService;
import com.qili.service.jc.JcProjectPayService;
import com.qili.service.jc.JcProjectService;
import com.qili.service.jc.JcProjectStageService;
import com.qili.service.supervisor.*;
import com.qili.service.supplier.ProjectPlaceService;
import com.qili.service.supplier.SupplierProjectAcceptService;
import com.qili.service.supplier.SupplierProjectManagerService;
import com.qili.service.sys.SysRegionService;
import com.qili.service.sys.SysUserWorkExperienceService;
import com.qili.util.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.formula.functions.T;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.ui.Model;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import tk.mybatis.mapper.entity.Example;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

import static java.util.Objects.isNull;

/**
 * @author zhaoyongke
 * @date 2021/6/24
 * @description
 */
@Controller
@Slf4j
@RequestMapping("/jc/projectCreate")
public class JcCreateController extends BaseController {

    @Autowired
    BaseStageJcService baseStageService;
    @Autowired
    ProjectLeaderService projectLeaderService;
    @Autowired
    JcProjectService jcProjectService;
    @Autowired
    BaseMilepostJcService baseMilepostService;
    @Autowired
    SysRegionService sysRegionService;
    @Autowired
    BaseDictService baseDictService;
    @Autowired
    BasePathConfigService basePathConfigService;
    @Autowired
    SysUserService sysUserService;
    @Autowired
    SysUserWorkExperienceService userWorkExperienceService;
    @Autowired
    BaseCompanyService baseCompanyService;
    @Autowired
    BaseCompanyOwnerService baseCompanyOwnerService;
    @Autowired
    ProjectContractService projectContractService;
    @Autowired
    ProjectAdminService projectAdminService;
    @Autowired
    JcProjectStageService jcProjectStageService;
    @Autowired
    JcProjectMilepostService jcProjectMilepostService;
    @Autowired
    SupervisorFileService jcFileService;
    @Autowired
    SupervisorFileTempService jcFileTempService;
    @Autowired
    SupplierProjectManagerService supplierProjectManagerService;
    @Autowired
    SupplierProjectAcceptService supplierProjectAcceptService;
    @Autowired
    JcProjectPayService jcProjectPayService;
    @Autowired
    ProjectNoticeServie projectNoticeServie;
    @Autowired
    ProjectUnitConstructionService projectUnitConstructionService;
    @Autowired
    ProjectPlaceService projectPlaceService;
    @Autowired
    ProjectBcUnitService projectBcUnitService;
    @Autowired
    private SupervisorFileService supervisorFileService;


    /**
     * @param model
     * @Author:zhaoyongke
     * @Description: 检测创建项目
     * @Date:15:09 2021/6/24
     */
    @GetMapping(value = "createIndex")
    @RequiresPermissions("jc:create")
    public String create(Model model) {

        /*        平台拥有方的市场人员和注册需方组织可在此处发布项目信息，
        如果是平台拥有方的市场人员则直接进入到发布页面，
        如果是注册需方组织则需要判断单位性质，
        单位性质为机关，则直接直接进入到发布页面，单位性质为企业，判断是否完善个人信息*/
        String userId = CommonUtil.getUserId();
        SysUser user1 = sysUserService.selectByPrimaryKey(userId);
        //单位性质
        String companyType = user1.getCompanyType();// 001 企业  002 机关
        //单位性质为机关，则直接直接进入到发布页面，单位性质为企业，判断是否完善个人信息  001 企业  002 机关
        if ("001".equals(companyType)) {
            String austatus = user1.getAuditStatus();
            if (!"1".equals(austatus)) {
                model.addAttribute("message", "企业信息不完善，请先去完善信息");
                model.addAttribute("messtype", "2");
                return "/error/message";
            }
        }

        /*项目来源*/
        List<BaseDict> projectSourcelist = DictUtil.getDictByType(DictTypes.PROJECT_SOURCE);
        /*项目类型*/
        List<BaseDict> projectTypeList = DictUtil.getDictByType(DictTypes.PROJECT_TYPEJC);
        /*监理形式*/
        List<BaseDict> checkShapeList = DictUtil.getDictByType(DictTypes.CHECK_SHAPE);
        /*是否续签*/
        List<BaseDict> isContinueList = DictUtil.getDictByType(DictTypes.IS_CONTINUE);
        /*行业类型*/
        List<BaseDict> AlstHyType = DictUtil.getDictByType(DictTypes.INDUSTRY);
        /*  付款次数 */
        List<BaseDict> payCountList = DictUtil.getDictByType(DictTypes.PAY_COUNT);
        /*  付款方式*/
        List<BaseDict> payList = DictUtil.getDictByType(DictTypes.PAY);
        /*  付款方式*/
        List<BaseCompany> AlstCompany = baseCompanyService.selectAll();
        // 项目归属
        List<BaseCompanyOwner> alstCompanyGs = baseCompanyOwnerService.selectAll();

        // 省
        List<SysRegion> provincelist = sysRegionService.selectListByLevelId("1");
        //当前用户
        SysUser user = sysUserService.selectByPrimaryKey(CommonUtil.getUserId());
        //获取监理合同额----监理实施细则里程碑显示阈值
        List<BaseDict> supervisorContractQuota = DictUtil.getDictByType(DictTypes.JLHTE);
        model.addAttribute("currId", CommonUtil.getUserId());
        model.addAttribute("user", user);
        model.addAttribute("projectTypeList", projectTypeList);
        model.addAttribute("provincelist", provincelist);
        model.addAttribute("projectSourcelist", projectSourcelist);
        model.addAttribute("checkShapeList", checkShapeList);
        model.addAttribute("isContinueList", isContinueList);
        model.addAttribute("payCountList", payCountList);
        model.addAttribute("hytypelist", AlstHyType);
        model.addAttribute("payList", payList);
        model.addAttribute("comlist", AlstCompany);
        model.addAttribute("comlistOwner", alstCompanyGs);
        model.addAttribute("supervisorContractQuota", supervisorContractQuota.size() > 0 ? supervisorContractQuota.get(0).getBadtLevel1() : "");
        model.addAttribute("jlssxzMilepost", "007");
        model.addAttribute("jlssxzMilepost2", "016");
        return "/jc/create/jc_create_project";
    }

    /**
     * @param jcProjectDTO
     * @Author:mr.hanchen
     * @Description:创建项目
     * @Date:9:32 2021/6/25
     */
    @RequestMapping("/createsave")
    @ResponseBody
    public JsonUtil addProcject(JcProjectDTO jcProjectDTO) {
        TrimUtil.trimBean(jcProjectDTO);
        //如果有id过来,说明不是第一次保存或者提交了,先彻底删除一遍旧的数据
        if (StringUtils.isNotBlank(jcProjectDTO.getId())) {
            //删除原项目相关数据:
            deleteAllAboutProject(jcProjectDTO.getId());
        }
        jcProjectDTO.setId(null);

        // 创建项目
        if (jcProjectDTO != null) {
            try {
                // 项目表
                JcProject jcProject = getSubvisorPrjObject(jcProjectDTO);
                /*校验项目名称是否重复*/
                JcProject projectnew = new JcProject();
                projectnew.setProjectName(jcProject.getProjectName());
                List<JcProject> list = jcProjectService.select(projectnew);
                if (list.size() > 0) {
                    JcProject jcProject1 = list.get(0);
                    SysUser sysUser = sysUserService.selectByPrimaryKey(jcProject1.getCreateBy());
                    return JsonUtil.error("创建项目失败:项目名称重复！该项目已经被项目经理" + sysUser.getRealName() + "创建");
                }
                // 插入项目主表数据
                boolean AbFlag = jcProjectService.insertSelective(jcProject) > 0;
                jcProjectDTO.setProjectId(jcProject.getId());
                if (AbFlag) {
                    // 项目负责人
                    saveLeader(jcProjectDTO);
                    // 阶段数据和里程数据
                    saveStage(jcProjectDTO, false);
                    saveBcUnit(jcProjectDTO);
                    // 付款方式
                    savePayWays(jcProjectDTO);
                    // 发送消息
                    saveSendNotice(jcProject);
                    // 保存合同签订地点
                    jcProjectService.addPalce(jcProjectDTO);
                    if ("002".equals(jcProjectDTO.getStatus())) {
                        // 管理员账号
                        saveAdmin(jcProjectDTO);
                        JcProjectMilepost milepostnew = new JcProjectMilepost();
                        milepostnew.setProjectId(jcProjectDTO.getProjectId());
                        List<JcProjectMilepost> milepostcurr = jcProjectMilepostService.select(milepostnew);
                        for (int x = 0; x < milepostcurr.size(); x++) {
                            saveSpecialMilePost(jcProjectDTO, milepostcurr.get(x));
                        }
                    }
                }
                JsonUtil result = new JsonUtil();
                result.setData(jcProject.getId());
                result.setFlag(true);
                result.setMsg("创建项目成功");
                return result;
            } catch (Exception e) {
                e.printStackTrace();
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                return JsonUtil.error("创建项目失败:" + e.getMessage());
            }
        } else {
            return JsonUtil.error("用户验证失败！！");
        }
    }

    /**
     * @Param
     * @author: HANCHEN
     * @Date: 11:43 2020/11/13
     * @Description: 获取前端传入数据 并塞入SupervisorProject实体类里面
     */
    public JcProject getSubvisorPrjObject(JcProjectDTO JcProjectDTO) throws Exception {
        JcProject jcProject = new JcProject();
        BeanUtil.copyNotNullBean(JcProjectDTO, jcProject);
        jcProject.setProjectName(jcProject.getProjectName().trim());
        JcProjectDTO.setProjectName(jcProject.getProjectName().trim());
        if (jcProject != null) {
            // 项目状态默认001 未启动
            //jcProject.setStatus("001");
            // 项目进度默认值是0
            BigDecimal bigDecimal = new BigDecimal(0);
            jcProject.setProgress(bigDecimal.toString());
            // 业务类型
            jcProject.setYwType("001");
            // 创建项目的创建时间
            jcProject.setCreateDate(new Date());
            String status = JcProjectDTO.getStatus();
            if ("002".equals(status)) {
                //记录提交时间
                jcProject.setCommitBy(CommonUtil.getUserId());
                jcProject.setCommitDate(DateUtil.getCurrentDateString());
            }
        }
        return jcProject;
    }

    /**
     * @param jcProjectDTO
     * @Author:HANCHEN
     * @Description:保存分包信息
     * @Date:14:37 2020/11/25
     */
    public void savePackage(JcProjectDTO jcProjectDTO) {
        ArrayList<ProjectContract> projectContractList = jcProjectDTO.getProjectContracts();
        if (projectContractList != null) {
            for (ProjectContract projectContract1 : projectContractList) {
                if (!isNull(projectContract1)) {
                    // 主表主键id
                    projectContract1.setProjectId(jcProjectDTO.getProjectId());
                    String AsPkId = projectContract1.getId();
                    if (StringUtil.isNotBlank(AsPkId)) {
                        //页面删除标志
                        Integer AiDelFlag = projectContract1.getOrderNum();
                        if ((AiDelFlag != null) && (AiDelFlag == -1)) {
                            //删除
                            projectContractService.deleteByPrimaryKey(AsPkId);
                        } else {
                            //修改
                            projectContractService.updateByPrimaryKeySelective(projectContract1);
                        }
                    } else {
                        //新增
                        projectContract1.setId(null);
                        projectContractService.insertSelective(projectContract1);
                    }
                }
            }
        }
    }

    public void saveBcUnit(JcProjectDTO jcProjectDTO) throws Exception {
        ArrayList<ProjectBcUnit> list = jcProjectDTO.getBcList();
        ProjectBcUnit projectBcUnit = new ProjectBcUnit();
        projectBcUnit.setProjectId(jcProjectDTO.getProjectId());
        projectBcUnitService.delete(projectBcUnit);
        for (ProjectBcUnit unit :
                list) {
            if (!"-1".equals(unit.getCreateBy())) {
                unit.setId(UUID.randomUUID().toString().replaceAll("-", ""));
                unit.setProjectId(jcProjectDTO.getProjectId());
                projectBcUnitService.insert(unit);
            }
        }
    }

    public void saveLeader(JcProjectDTO jcProjectDTO) throws Exception {
        ArrayList<ProjectLeaderDTO> projectLeaderList = jcProjectDTO.getProjectLeaders();
        if (projectLeaderList != null) {
            String AsPrjId = jcProjectDTO.getProjectId();
            for (ProjectLeaderDTO projectLeader : projectLeaderList) {
                if (!isNull(projectLeader)) {
                    projectLeader.setSupervisorProjectId(AsPrjId);

                    String AsPlId = projectLeader.getId();
                    if (StringUtil.isNotBlank(AsPlId)) {
                        //页面删除标志
                        String AsDelFlag = projectLeader.getCreateBy();
                        if (StringUtil.isNotBlank(AsDelFlag) && (AsDelFlag.equals("-1"))) {
                            //删除
                            projectLeaderService.deleteByPrimaryKey(AsPlId);
                        } else {
                            //修改
                            String AsRealName = projectLeader.getRealName();
                            String AsProjectLeader = projectLeader.getProjectLeader();
                            SysUser sysUser = sysUserService.selectByPrimaryKey(AsProjectLeader);
                            if (isNull(sysUser)) {
                                String owerCompany = jcProjectDTO.getOwerCompany();
                                SysUser user = createUserForFZR(projectLeader, owerCompany);
                                projectLeader.setProjectLeader(user.getId());
                            } else {
                                if (!sysUser.getUsername().equals(AsRealName)) {
//                                    sysUserService.deleteByPrimaryKey(AsProjectLeader);
                                    String owerCompany = jcProjectDTO.getOwerCompany();
                                    SysUser user = createUserForFZR(projectLeader, owerCompany);
                                    projectLeader.setProjectLeader(user.getId());
                                }
                            }
                            projectLeaderService.updateByPrimaryKeySelective(projectLeader);
                        }
                    } else {
                        //新增
                        // 创建业主单位负责人账号  判断单位的名字是否存在
                        String owerCompany = jcProjectDTO.getOwerCompany();
                        SysUser user = createUserForFZR(projectLeader, owerCompany);
                        ProjectLeader leader = new ProjectLeader();
                        BeanUtil.copyNotNullBean(projectLeader, leader);
                        leader.setId(null);
                        leader.setProjectLeader(user.getId());
                        projectLeaderService.insertSelective(leader);
                    }
                }
            }
        }
    }

    /*
     * @Author:mr.hanchen
     * @Description:为负责人创建账号
     * @param projectLeader
     * @param owerCompany
     * @Date:11:00 2021/6/25
     */
    public SysUser createUserForFZR(ProjectLeaderDTO projectLeader, String owerCompany) {
        // 负责人名字
        String AsRealName = projectLeader.getRealName();
        SysUser AoUser = new SysUser();
        AoUser.setUsername(AsRealName);
        AoUser.setCompanyName(owerCompany);

        //设置默认需方
        AoUser.setGxType("002");
        //设置默认组织
        AoUser.setPersonType("002");
        //设置默认业务类型
//        AoUser.setYwType("001");
        //设置默认项目创建:002
        AoUser.setSource("002");
/*        if(StringUtils.isNotBlank(projectLeader.getDuty())){
            SysUserWorkExperience nowWork = new SysUserWorkExperience();
            nowWork.setDuty(projectLeader.getDuty());
            AoUser.setNowWork(nowWork);
        }*/
        saveNewUserIdForProjectLeaderAndUnits(AoUser);

        List<String> userRoleNameList = new ArrayList<String>();
        userRoleNameList.add("jsdwxmfzr");
        sysUserService.setMenuAndRolesWhenRegist(AoUser, userRoleNameList);
        return AoUser;

    }

    /**
     * 注册新用户,
     * 查找系统中是否存在同名用户
     * 如果存在同名用户,
     * 如果同一个公司中存在同名用户,给user设置id为该同名用户id
     * 如果同名用户不为同一个公司,那么根据规则生成新用户,给user设置新生成的用户id
     *
     * @param user
     * @return
     */
    public void saveNewUserIdForProjectLeaderAndUnits(SysUser user) {
        SysUser sameNameUser = new SysUser();
        sameNameUser.setRealName(user.getUsername());
        //查询同名的用户
        List<SysUser> listuser = sysUserService.select(sameNameUser);
        Integer count = 0;
        if (listuser.size() > 0) {
            //存在相同username的账号
       /*     SysUser realNameUser = new SysUser();
            realNameUser.setRealName(user.getUsername());
            List<SysUser> listuserReal = sysUserService.select(realNameUser);*/
            for (int i = 0; i < listuser.size(); i++) {
                //相同公司 相同姓名
                SysUser dbUser = listuser.get(i);
                String dbCompanyName = dbUser.getCompanyName() + "";
                String dbRealName = dbUser.getRealName() + "";
                if (dbRealName.equals(user.getUsername()) && user.getCompanyName().equals(dbCompanyName)) {
                    // 相同姓名 相同公司
                    user.setId(dbUser.getId());
                    return;
                } else if (dbRealName.equals(user.getUsername()) && !user.getCompanyName().equals(dbCompanyName)) {
                    // 相同姓名不同公司
                    count++;
                } else {
                    //不同姓名 公司相同、不同姓名不同公司
                    count++;
                }
            }
        }
        //生成账号
        SysUser newUser = new SysUser();
        //获取用户名
        String username = getUserName(user, count);
        newUser.setUsername(username);
        newUser.setCompanyName(user.getCompanyName());
        newUser.setPassword("12345678");
        newUser.setRealName(user.getUsername());
        newUser.setGxType(user.getGxType());
        newUser.setYwType(user.getYwType());
        newUser.setPersonType(user.getPersonType());
        newUser.setSource(user.getSource());
        newUser.setCreateDate(DateUtil.getCurrentDateTime());
        sysUserService.setUserFilePath(newUser);
        sysUserService.insertSelective(newUser);

        SysUserWorkExperience nowWork = user.getNowWork();
        if (nowWork != null) {
            sysUserService.setUserFilePath(newUser);
            nowWork.setIfNow("1");
            nowWork.setSuId(newUser.getId());
            userWorkExperienceService.insertSelective(nowWork);
        }

        user.setId(newUser.getId());
        user.setUsername(newUser.getUsername());
        user.setRealName(newUser.getRealName());
    }

    public String getUserName(SysUser user, int count) {
        String userName = setUserName(user, count);
        int countUser = sysUserService.checkUser(userName);
        if (countUser != 0) {
            count = count + 1;
            userName = setUserName(user, count);
            int countUser1 = sysUserService.checkUser(userName);
            if (countUser1 > 0) {
                userName = getUserName(user, count);
            }
        }
        return userName;
    }

    /**
     * @param user
     * @param count
     * @Author:mr.hanchen
     * @Description:设置用户名
     * @Date:11:02 2021/6/25
     */
    public String setUserName(SysUser user, int count) {
        SysUser newUser = new SysUser();
        if (count > 0) {
            newUser.setUsername(user.getUsername() + "0" + count);
        } else {
            newUser.setUsername(user.getUsername());
        }
        return newUser.getUsername();
    }

    /**
     * 创建管理员账号
     *
     * @param jcProjectDTO
     */
    public void saveAdmin(JcProjectDTO jcProjectDTO) {
        //业主单位
        String ownCompany = jcProjectDTO.getOwerCompany();
        if (StringUtils.isBlank(ownCompany)) {
            throw new RuntimeException("创建建设单位管理员账号时,没有获取到业主单位名称");
        }
        String province = jcProjectDTO.getProvince();
        if (StringUtils.isBlank(province)) {
            throw new RuntimeException("创建建设单位管理员账号时,没有获取到合同签订地点的省份编码");
        }
        SysRegion sr = new SysRegion();
        sr.setCode(province);
        List<SysRegion> addressList = sysRegionService.select(sr);
        SysRegion provinceRegion = new SysRegion();
        if (addressList.size() > 0) {
            provinceRegion = addressList.get(0);
        } else {
            throw new RuntimeException("创建建设单位管理员账号时,没有获取到合同签订地点的省份");
        }
        String newUserName = sysUserService.getNewUserName(provinceRegion.getName());
        newUserName = sysUserService.checkAndHandlerSameNewUserName(newUserName);
        SysUser sysUser = new SysUser();
        sysUser.setUsername(newUserName);
        sysUser.setRealName(ownCompany);
        sysUser.setGxType("002");
        sysUser.setPassword("12345678");
        sysUser.setCompanyName(jcProjectDTO.getOwerCompany());
        //设置默认组织
        sysUser.setPersonType("002");
        //设置为自行注册
        sysUser.setSource("003");
        sysUserService.setUserFilePath(sysUser);
        sysUserService.insertSelective(sysUser);
        projectAdminService.insertSelective(ProjectAdmin.builder().spId(jcProjectDTO.getProjectId()).uId(sysUser.getId()).build());
        List<String> userRoleNameList = new ArrayList<String>();
        userRoleNameList.add("jsdwglry");
        sysUserService.setMenuAndRolesWhenRegist(sysUser, userRoleNameList);
    }

    /*
     * @Author:mr.hanchen
     * @Description:
     * @param jcProjectDTO
     * @param pModify
     * @Date:11:10 2021/6/25
     */
    public void saveStage(JcProjectDTO jcProjectDTO, boolean pModify) throws Exception {
        ArrayList<JcProjectStage> supervisorProjectStageList = jcProjectDTO.getJcProjectStages();
        if(!"001".equals( jcProjectDTO.getStatus())){
            checkStageDate(supervisorProjectStageList);
        }
        ArrayList<JcProjectMilepost> jcProjectMilepostList = jcProjectDTO.getJcProjectMileposts();
        if (supervisorProjectStageList != null) {
            String AsPrjId = jcProjectDTO.getProjectId();
            JcProjectStage AoSuperPrjStage = supervisorProjectStageList.get(0);
            String AsFlag = AoSuperPrjStage.getCreateBy();
            //修改状态下，而且没有从服务器加载的标记，删除项目原阶段和里程
            if (pModify && (StringUtil.isBlank(AsFlag))) {
                String[] AyPrjIds = new String[]{AsPrjId};
                jcProjectStageService.deleteByProjectIds(AyPrjIds);
                jcProjectMilepostService.deleteByProjectIds(AyPrjIds);
            }
            for (int i = 0; i < supervisorProjectStageList.size(); i++) {
                AoSuperPrjStage = supervisorProjectStageList.get(i);
                if (!isNull(AoSuperPrjStage)) {
                    AsFlag = AoSuperPrjStage.getCreateBy();
                    AoSuperPrjStage.setCreateBy("");
                    if (StringUtil.isNotBlank(AsFlag) && (AsFlag.equals("-1"))) {

                        //修改
                        if (StringUtils.isNotBlank(AoSuperPrjStage.getStatus())) {
                            //选中的修改,没选中的删除
                            if ("1".equals(AoSuperPrjStage.getStatus())) {
                                jcProjectStageService.updateByPrimaryKeySelective(AoSuperPrjStage);
                            } else if ("0".equals(AoSuperPrjStage.getStatus())) {
                                jcProjectStageService.deleteByPrimaryKey(AoSuperPrjStage);
                            }
                        }
                        //处理里程的修改
                        for (JcProjectMilepost item : jcProjectMilepostList) {
                            String itemStageId = item.getSupervisorProjectStageId();
                            if (!isNull(itemStageId) && (AoSuperPrjStage.getId().equals(itemStageId))) {
                                if (!isNull(item) && StringUtils.isNotBlank(item.getStatus())) {
                                    if ("1".equals(item.getStatus())) {
                                        if ("001".equals(item.getMilepostNo()) && "001".equals(jcProjectDTO.getStatus())) {
                                            //宇宙无敌超级大帅比韩晨2021年6月23日10:03:12 修改:编辑项目基本信息是否续签改变监理招标文件监理投标文件的状态
                                            if ("001".equals(jcProjectDTO.getIsContinue())) {
                                                item.setStepNum("12,22,30,40,50,60,70,90");
                                                item.setFinishStatus("2");
                                            } else {
                                                item.setStepNum("10,20,30,40,50,60,70,90");
                                            }
                                        }
                                        jcProjectMilepostService.updateByPrimaryKeySelective(item);
                                    } else if ("0".equals(item.getStatus())) {
                                        jcProjectMilepostService.deleteByPrimaryKey(item);
                                    }
                                }
                            }
                        }
                    } else {
                        if ("1".equals(AoSuperPrjStage.getStatus()) || pModify) {
                            //新增
                            String AsWebStageId = AoSuperPrjStage.getId();
                            String AsStageId = IdUtil.simpleUUID();
                            AoSuperPrjStage.setId(AsStageId);
                            AoSuperPrjStage.setFinishStatus("0");
                            // 主项目id
                            AoSuperPrjStage.setProjectId(AsPrjId);
                            jcProjectStageService.insertSelective(AoSuperPrjStage);
                            for (JcProjectMilepost item : jcProjectMilepostList) {
                                if (!isNull(item) && ("1".equals(item.getStatus()) || pModify)) {
                                    String AsStateId = item.getSupervisorProjectStageId();
                                    if (StringUtil.isNotBlank(AsStateId)) {
                                        if (AsStateId.equals(AsWebStageId)) {
                                            item.setSupervisorProjectStageId(AsStageId);
                                            saveMeilPost(jcProjectDTO, item);
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
        /*处理其他监理工作阶段*/
        saveOrUpdateQtJlStage(jcProjectDTO);
    }

    /**
     * @param supervisorProjectStageList
     * @Author:zhaoyongke
     * @Description: 校验阶段 时间 是否连续
     * @Date:9:25 2022/7/6
     */
    public void checkStageDate(ArrayList<JcProjectStage> supervisorProjectStageList) throws Exception {
        if (!CollectionUtils.isEmpty(supervisorProjectStageList)) {
            if (supervisorProjectStageList.size() > 1) {
                List<JcProjectStage> list = supervisorProjectStageList.stream().filter(stage -> "1".equals(stage.getStatus())).collect(Collectors.toList());
                list.sort(Comparator.comparing(JcProjectStage::getStageNo));
                System.out.println("=========================================");
                System.out.println(list);
                for (int i = 0; i < list.size(); i++) {
                    JcProjectStage jcProjectStage = list.get(i);
                    // 当前时间段的开始时间
                    String startDate = jcProjectStage.getStartDate();
                    String endDate = jcProjectStage.getEndDate();
                    if(StringUtil.isBlank(startDate)  || StringUtil.isBlank(endDate) ){
                        throw new Exception("阶段时间不能为空");
                    }
                    if (i < list.size() - 1) {
                        // 下一个时间的开始时间
                        String NextstartDate = list.get(i + 1).getStartDate();
                        if(StringUtil.isBlank(NextstartDate)){
                            throw new Exception("阶段时间不能为空");
                        }
                        Boolean isTrue = DateUtil.isContinuation(NextstartDate, endDate);
                        if (!isTrue) {
                            throw new Exception("阶段时间不连续"+endDate+"------"+NextstartDate);
                        }
                    }
                }

            }


        }

    }

    /*
     * @Author:mr.hanchen
     * @Description:保存项目里程
     * @param jcProjectDTO
     * @param jcProjectMilepost
     * @Date:13:21 2021/6/25
     */
    public void saveMeilPost(JcProjectDTO jcProjectDTO, JcProjectMilepost jcProjectMilepost) throws Exception {
        if (jcProjectMilepost != null) {
            // 项目主键
            jcProjectMilepost.setProjectId(jcProjectDTO.getProjectId());
            // 状态
            jcProjectMilepost.setStatus("1");
            // 完成状态
            jcProjectMilepost.setFinishStatus("0");
            /*是否续签 001 是 000 否*/
            String isContinue = jcProjectDTO.getIsContinue() + "";
            String milepostno = jcProjectMilepost.getMilepostNo() + "";
            /*选择是否续签 是 则招标文件里程中  监理招标文件和监理投标文件 默认已完成*/
            if ("001".equals(milepostno)) {
                if ("001".equals(isContinue)) {
                    jcProjectMilepost.setStepNum("12,22,30,40,50,60,70,90");
                    jcProjectMilepost.setFinishStatus("2");
                    jcProjectMilepost.setFinishDate(DateUtil.getCurrentDateTimeString());
                }
            }
            jcProjectMilepostService.insertSelective(jcProjectMilepost);
            //特殊处理里程
//             doSpecialMilePost(jcProjectDTO, jcProjectMilepost);
        }
    }

    public void updateCopyGxhTFile(JcProjectDTO jcProjectDTO, String AsFileConfigId, JcProjectMilepost jcProjectMilepost, String AsFileType, String AsFileStuffix) throws Exception {

        SupervisorFileTemp jcFileTemp = new SupervisorFileTemp();
        jcFileTemp.setLinkId(jcProjectDTO.getSupProjectId());
        jcFileTemp.setType("314");
        List<SupervisorFileTemp> selectzb = jcFileTempService.select(jcFileTemp);
        int zbnum = 1;
        for (int i = 0; i < selectzb.size(); i++) {
            SupervisorFile jcFile = new SupervisorFile();
            jcFile.setProjectId(jcProjectDTO.getProjectId());
            jcFile.setStageId(jcProjectMilepost.getSupervisorProjectStageId());
            jcFile.setSpmId(jcProjectMilepost.getId());
            jcFile.setType(AsFileType);
            SupervisorFileTemp supervisorFileTemp1 = selectzb.get(i);
            UploadType uploadType = UploadType.getEnumByType(0);
            uploadType.setFilePathId(AsFileConfigId);
            String pNo = "00" + zbnum;
            String AsFileName = FileUtils.getFileNameByNoJc(jcProjectDTO.getProjectName(), AsFileType, "", ".pdf", pNo);
            uploadType.setFileName(AsFileName);
            List<String> AlstPlaceHolder = new ArrayList<>();
            AlstPlaceHolder.add(jcProjectDTO.getProjectName());
            uploadType.setPlaceholder(AlstPlaceHolder);
            String AsFilePath = FilePathUtil.getFullSavePathAndNameByConfigFileId(uploadType);
            jcFile.setUrl(supervisorFileTemp1.getUrl());
            jcFile.setFileName(AsFileName);
            jcFile.setInd(zbnum);
            jcFile.setFileType(".pdf");
            // 从供需复制而来
            jcFile.setCreateType("1");
//            if (FileUtils.CopyFile(supervisorFileTemp1.getUrl(), AsFilePath)) {
            jcFileService.insertSelective(jcFile);
//            } else {
//                throw new Exception("复制文件出现异常");
//            }
            zbnum++;
        }
        SupervisorFileTemp jcFileTempHtsm = new SupervisorFileTemp();
        jcFileTempHtsm.setLinkId(jcProjectDTO.getSupProjectId());
        jcFileTempHtsm.setType("315");
        List<SupervisorFileTemp> selectzbSm = jcFileTempService.select(jcFileTempHtsm);
        for (int i = 0; i < selectzbSm.size(); i++) {
            SupervisorFile jcFile = new SupervisorFile();
            jcFile.setProjectId(jcProjectDTO.getProjectId());
            jcFile.setStageId(jcProjectMilepost.getSupervisorProjectStageId());
            jcFile.setSpmId(jcProjectMilepost.getId());
            jcFile.setType(AsFileType);
            SupervisorFileTemp supervisorFileTemp1 = selectzbSm.get(i);
            UploadType uploadType = UploadType.getEnumByType(0);
            uploadType.setFilePathId(AsFileConfigId);
            String pNo = "00" + zbnum;
            String AsFileName = FileUtils.getFileNameByNoJc(jcProjectDTO.getProjectName(), AsFileType, "", AsFileStuffix, pNo);
            uploadType.setFileName(AsFileName);
            List<String> AlstPlaceHolder = new ArrayList<>();
            AlstPlaceHolder.add(jcProjectDTO.getProjectName());
            uploadType.setPlaceholder(AlstPlaceHolder);
            String AsFilePath = FilePathUtil.getFullSavePathAndNameByConfigFileId(uploadType);
            jcFile.setUrl(supervisorFileTemp1.getUrl());
            jcFile.setFileName(AsFileName.replace("监理合同", "监理合同说明"));
            jcFile.setInd(zbnum);
            jcFile.setFileType(FilePathUtil.getFileSufiix(AsFileName));
            // 从供需复制而来
            jcFile.setCreateType("1");
//            if (FileUtils.CopyFile(supervisorFileTemp1.getUrl(), AsFilePath)) {
            jcFileService.insertSelective(jcFile);
//            } else {
//                throw new Exception("复制文件出现异常");
//            }
            zbnum++;
        }
    }

    public void updateCopyGxZbFile(JcProjectDTO jcProjectDTO, String AsFileConfigId, JcProjectMilepost jcProjectMilepost, String AsFileType, String AsFileStuffix) throws Exception {

        SupervisorFileTemp jcFileTemp = new SupervisorFileTemp();
        jcFileTemp.setLinkId(jcProjectDTO.getSupProjectId());
        jcFileTemp.setType("311");//招标文件 说明
        List<SupervisorFileTemp> selectzb = jcFileTempService.select(jcFileTemp);
        int zbnum = 1;
        for (int i = 0; i < selectzb.size(); i++) {
            SupervisorFile jcFile = new SupervisorFile();
            jcFile.setProjectId(jcProjectDTO.getProjectId());
            jcFile.setStageId(jcProjectMilepost.getSupervisorProjectStageId());
            jcFile.setSpmId(jcProjectMilepost.getId());
            jcFile.setType(AsFileType);
            SupervisorFileTemp supervisorFileTemp1 = selectzb.get(i);
            UploadType uploadType = UploadType.getEnumByType(0);
            uploadType.setFilePathId(AsFileConfigId);
            String pNo = "00" + zbnum;
            String AsFileName = FileUtils.getFileNameByNoJc(jcProjectDTO.getProjectName(), AsFileType, "", AsFileStuffix, pNo);
            uploadType.setFileName(AsFileName);
            List<String> AlstPlaceHolder = new ArrayList<>();
            AlstPlaceHolder.add(jcProjectDTO.getProjectName());
            uploadType.setPlaceholder(AlstPlaceHolder);
            String AsFilePath = FilePathUtil.getFullSavePathAndNameByConfigFileId(uploadType);
            jcFile.setUrl(supervisorFileTemp1.getUrl());
            jcFile.setFileName(AsFileName.replace("检测招标文件", "检测招标文件说明"));
            jcFile.setInd(zbnum);
            jcFile.setFileType(FilePathUtil.getFileSufiix(AsFileName));
            // 从供需复制而来
            jcFile.setCreateType("1");
//            if (FileUtils.CopyFile(supervisorFileTemp1.getUrl(), AsFilePath)) {
            jcFileService.insertSelective(jcFile);
//            } else {
//                throw new Exception("复制文件出现异常");
//            }
            zbnum++;
        }
        SupervisorFileTemp jcFileTempHtsm = new SupervisorFileTemp();
        jcFileTempHtsm.setLinkId(jcProjectDTO.getSupProjectId());
        jcFileTempHtsm.setType("312");//招标文件
        List<SupervisorFileTemp> selectzbSm = jcFileTempService.select(jcFileTempHtsm);
        for (int i = 0; i < selectzbSm.size(); i++) {
            SupervisorFile jcFile = new SupervisorFile();
            jcFile.setProjectId(jcProjectDTO.getProjectId());
            jcFile.setStageId(jcProjectMilepost.getSupervisorProjectStageId());
            jcFile.setSpmId(jcProjectMilepost.getId());
            jcFile.setType(AsFileType);
            SupervisorFileTemp supervisorFileTemp1 = selectzbSm.get(i);
            UploadType uploadType = UploadType.getEnumByType(0);
            uploadType.setFilePathId(AsFileConfigId);
            String pNo = "00" + zbnum;
            String AsFileName = FileUtils.getFileNameByNoJc(jcProjectDTO.getProjectName(), AsFileType, "", AsFileStuffix, pNo);
            uploadType.setFileName(AsFileName);
            List<String> AlstPlaceHolder = new ArrayList<>();
            AlstPlaceHolder.add(jcProjectDTO.getProjectName());
            uploadType.setPlaceholder(AlstPlaceHolder);
            String AsFilePath = FilePathUtil.getFullSavePathAndNameByConfigFileId(uploadType);
            jcFile.setUrl(supervisorFileTemp1.getUrl());
            jcFile.setFileName(AsFileName);
            jcFile.setInd(zbnum);
            jcFile.setFileType(FilePathUtil.getFileSufiix(AsFileName));
            // 从供需复制而来
            jcFile.setCreateType("1");
//            if (FileUtils.CopyFile(supervisorFileTemp1.getUrl(), AsFilePath)) {
            jcFileService.insertSelective(jcFile);
//            } else {
//                throw new Exception("复制文件出现异常");
//            }
            zbnum++;
        }
    }

    public void updateCopyGxTbFile(JcProjectDTO jcProjectDTO, String AsFileConfigId, JcProjectMilepost jcProjectMilepost, String AsFileType, String AsFileStuffix) throws Exception {

        SupervisorFileTemp jcFileTemp = new SupervisorFileTemp();
        jcFileTemp.setLinkId(jcProjectDTO.getSupProjectId());
        jcFileTemp.setType("313");//投标文件
        List<SupervisorFileTemp> selectzb = jcFileTempService.select(jcFileTemp);
        int zbnum = 1;
        for (int i = 0; i < selectzb.size(); i++) {
            SupervisorFile jcFile = new SupervisorFile();
            jcFile.setProjectId(jcProjectDTO.getProjectId());
            jcFile.setStageId(jcProjectMilepost.getSupervisorProjectStageId());
            jcFile.setSpmId(jcProjectMilepost.getId());
            jcFile.setType(AsFileType);
            SupervisorFileTemp supervisorFileTemp1 = selectzb.get(i);
            UploadType uploadType = UploadType.getEnumByType(0);
            uploadType.setFilePathId(AsFileConfigId);
            String pNo = "00" + zbnum;
            String AsFileName = FileUtils.getFileNameByNoJc(jcProjectDTO.getProjectName(), AsFileType, "", AsFileStuffix, pNo);
            uploadType.setFileName(AsFileName);
            List<String> AlstPlaceHolder = new ArrayList<>();
            AlstPlaceHolder.add(jcProjectDTO.getProjectName());
            uploadType.setPlaceholder(AlstPlaceHolder);
            String AsFilePath = FilePathUtil.getFullSavePathAndNameByConfigFileId(uploadType);
            jcFile.setUrl(supervisorFileTemp1.getUrl());
            jcFile.setFileName(AsFileName);
            jcFile.setInd(zbnum);
            jcFile.setFileType(FilePathUtil.getFileSufiix(AsFileName));
            // 从供需复制而来
            jcFile.setCreateType("1");
//            if (FileUtils.CopyFile(supervisorFileTemp1.getUrl(), AsFilePath)) {
            jcFileService.insertSelective(jcFile);
//            } else {
//                throw new Exception("复制文件出现异常");
//            }
            zbnum++;
        }
        // 查询迎接
        SupplierProject supplierProject = supplierProjectManagerService.selectByPrimaryKey(jcProjectDTO.getSupProjectId());
        SupplierProjectAccept accept = new SupplierProjectAccept();
        accept.setSupProjectId(supplierProject.getSupProjectId());
        accept.setAcceptBy(supplierProject.getZbBy());
        List<SupplierProjectAccept> selectAccept = supplierProjectAcceptService.select(accept);
        for (int i = 0; i < selectAccept.size(); i++) {
            SupplierProjectAccept accept1 = selectAccept.get(i);
            SupervisorFileTemp supervisorFileTempaccept = new SupervisorFileTemp();
            supervisorFileTempaccept.setLinkId(accept1.getSupAcceptId());
            supervisorFileTempaccept.setType("301");//投标文件
            List<SupervisorFileTemp> selecttbaccept = jcFileTempService.select(supervisorFileTempaccept);
            for (int j = 0; j < selecttbaccept.size(); j++) {
                SupervisorFile jcFile = new SupervisorFile();
                jcFile.setProjectId(jcProjectDTO.getProjectId());
                jcFile.setStageId(jcProjectMilepost.getSupervisorProjectStageId());
                jcFile.setSpmId(jcProjectMilepost.getId());
                jcFile.setType(AsFileType);
                SupervisorFileTemp supervisorFileTemp1 = selecttbaccept.get(i);
                UploadType uploadType = UploadType.getEnumByType(0);
                uploadType.setFilePathId(AsFileConfigId);
                String pNo = "00" + zbnum;
                String AsFileName = FileUtils.getFileNameByNoJc(jcProjectDTO.getProjectName(), AsFileType, "", AsFileStuffix, pNo);
                uploadType.setFileName(AsFileName);
                List<String> AlstPlaceHolder = new ArrayList<>();
                AlstPlaceHolder.add(jcProjectDTO.getProjectName());
                uploadType.setPlaceholder(AlstPlaceHolder);
                String AsFilePath = FilePathUtil.getFullSavePathAndNameByConfigFileId(uploadType);
                jcFile.setUrl(supervisorFileTemp1.getUrl());
                jcFile.setFileName(AsFileName);
                jcFile.setInd(zbnum);
                jcFile.setFileType(FilePathUtil.getFileSufiix(AsFileName));
                // 从供需复制而来
                jcFile.setCreateType("1");
//                if (FileUtils.CopyFile(supervisorFileTemp1.getUrl(), AsFilePath)) {
                jcFileService.insertSelective(jcFile);
//                } else {
//                    throw new Exception("复制文件出现异常");
//                }
                zbnum++;

            }
        }


    }


    public void saveOrUpdateQtJlStage(JcProjectDTO jcProjectDTO) throws Exception {
        /*查询是否含有其他阶段*/
        JcProjectStage stage = new JcProjectStage();
        stage.setProjectId(jcProjectDTO.getProjectId());
        stage.setStageNo("005");
        List<JcProjectStage> stageListqt = jcProjectStageService.select(stage);
        /*查询是否有四大阶段*/
        Example e = new Example(JcProjectStage.class);
        Example.Criteria c = e.createCriteria();
        c.andEqualTo("projectId", jcProjectDTO.getProjectId());
        c.andNotEqualTo("stageNo", "005");
        int countstage = jcProjectStageService.selectCountByExample(e);
        if (stageListqt.size() == 0) {
            if (countstage > 0) {
                /*添加该阶段*/
                String AsStageId = IdUtil.simpleUUID();
                stage.setId(AsStageId);
                stage.setFinishStatus("0");
                // 主项目id
                stage.setProjectId(jcProjectDTO.getProjectId());
                JcProjectStageDTO dtoorder = new JcProjectStageDTO();
                dtoorder.setProjectId(jcProjectDTO.getProjectId());
                /*查询最大排序*/
                Integer orderNum = jcProjectStageService.selectProjectStageMaxOrderNum(dtoorder) + 1;
                stage.setOrderNum(orderNum);
                jcProjectStageService.insertSelective(stage);
                // 保存里程
                BaseStageJc basestage = new BaseStageJc();
                basestage.setStageNo("005");
                basestage.setProjectTypeNo(jcProjectDTO.getProjectType());
                List<BaseStageJc> listbasestage = baseStageService.select(basestage);
                if (listbasestage.size() > 0) {
                    basestage = listbasestage.get(0);
                }
                String baseStageId = basestage.getId();
                List<BaseMilepostJc> baselistmilepost = baseMilepostService.selectMilepostListByStageId(baseStageId, DictTypes.PROJECT_MILEPOST_JC.getType());
                for (int i = 0; i < baselistmilepost.size(); i++) {
                    BaseMilepostJc baseMilepost = baselistmilepost.get(i);
                    JcProjectMilepost milepost = new JcProjectMilepost();
                    String MilepostId = IdUtil.simpleUUID();
                    milepost.setId(MilepostId);
                    milepost.setProjectId(jcProjectDTO.getProjectId());
                    milepost.setMilepostNo(baseMilepost.getMilepostNo());
                    milepost.setStatus("1");
                    milepost.setSpmBaseMilePostId(baseMilepost.getId());
                    String enjc = baseMilepost.getMilepostEnjc() + "";
                    if (StringUtil.isBlank(enjc)) {
                        milepost.setPercentage("0");
                    } else {
                        milepost.setPercentage(baseMilepost.getMilepostEnjc());
                    }
                    milepost.setSupervisorProjectStageId(AsStageId);
                    /*变更处理  变更统计表*/
//                    doSpecialMilePost(jcProjectDTO, milepost);
                    jcProjectMilepostService.insertSelective(milepost);
                }

            }

        }
    }

    /*
     * @Author:mr.hanchen
     * @Description:
     * @param jcProjectDTO
     * @Date:14:14 2021/6/25
     */
    public void savePayWays(JcProjectDTO jcProjectDTO) {
        List<JcProjectPayDTO> AlstPayWays = jcProjectDTO.getPayList();
        if (!isNull(AlstPayWays)) {
            String AsPrjId = jcProjectDTO.getProjectId();
            for (JcProjectPayDTO item : AlstPayWays) {
                if (!isNull(item)) {
                    JcProjectPay jcProjectPay = new JcProjectPay();
                    BeanUtil.copyNotNullBean(item, jcProjectPay);
                    jcProjectPay.setSppPrjid(AsPrjId);
                    String AsId = jcProjectPay.getSppId();
                    if (StringUtils.isNotBlank(jcProjectPay.getSppNo())) {
                        if (StringUtil.isNotBlank(AsId)) {
                            //页面删除标志
                            String AsDelFlag = jcProjectPay.getSppNote();
                            if (StringUtil.isNotBlank(AsDelFlag) && (AsDelFlag.equals("-1"))) {
                                //删除
                                jcProjectPayService.deleteByPrimaryKey(AsId);
                            } else {
                                //修改
                                String persent = jcProjectPay.getSppPersent();
                                if (StringUtil.isNotBlank(persent)) {
                                    if (persent.indexOf("%") < 0) {
                                        jcProjectPay.setSppPersent(persent + "%");
                                    }
                                }
                                jcProjectPayService.updateByPrimaryKeySelective(jcProjectPay);
                            }
                        } else {
                            //新增
                            jcProjectPay.setSppId(null);
                            String persent = jcProjectPay.getSppPersent();
                            if (StringUtil.isNotBlank(persent)) {
                                if (persent.indexOf("%") < 0) {
                                    jcProjectPay.setSppPersent(persent + "%");
                                }
                            }
                            String AsDelFlag = jcProjectPay.getSppNote();
                            if (!"-1".equals(AsDelFlag)) {
                                jcProjectPayService.insertSelective(jcProjectPay);
                            }
                        }
                    }
                }
            }
        }
    }

    /**
     * @param jcProject
     * @Author:mr.hanchen
     * @Description:消息提醒表
     * @Date:14:27 2021/6/25
     */
    public void saveSendNotice(JcProject jcProject) {
        ProjectNotice notice = new ProjectNotice();
        notice.setLinkId(jcProject.getId());
        notice.setIsView("0");
        notice.setSendTo(jcProject.getCreateBy());
        notice.setTitle(jcProject.getProjectName() + "甲方乙方账户创建成功");
        notice.setNoticeType("001");//通知类型 账号通知 001  流程进展通知002  服务评价 003
        notice.setApplicantType("001");// 监理
        projectNoticeServie.insertSelective(notice);
    }

    /**
     * @param project
     * @Author:zhaoyongke
     * @Description: 获取公司信息
     * @Date:10:17 2021/3/18
     */
    @GetMapping(value = "getCompany")
    @ResponseBody
    public JsonUtil getCompany(JcProjectDTO project) {
        JsonUtil re = new JsonUtil();
        try {
            List<BaseCompany> AlstCompany = baseCompanyService.selectAll();
            re.setFlag(true);
            re.setData(AlstCompany);
            return re;
        } catch (Exception e) {
            e.printStackTrace();
            re.setFlag(false);
            re.setMsg("获取公司异常！！" + e.getMessage());
            return re;
        }
    }

    /**
     * @Param
     * @author: zhanghuawei
     * @Date: 11:41 2020/11/13
     * @Description: 查询baseStage表
     */
    @RequestMapping(value = "/baseStage")
    @ResponseBody
    public JsonUtil selectBaseStage(String projectTypeNo) {
        JsonUtil jsonUtil = new JsonUtil();
        BaseStageMileDTO baseStageDto = new BaseStageMileDTO();
        if (projectTypeNo != null) {
            baseStageDto.setProjectTypeNo(projectTypeNo);
            List<BaseStageMileDTO> baseStageDtoList = baseStageService.selectStageMileByProjectType(baseStageDto);
            if (baseStageDtoList != null) {
                jsonUtil.setData(baseStageDtoList);
                return jsonUtil;
            }
        }
        return null;
    }

    /**
     * 删除项目相关信息
     *
     * @param id
     */
    public void deleteAllAboutProject(String id) {
        if (StringUtils.isNotBlank(id)) {
            //删除leader:
            ProjectLeader delLeader = new ProjectLeader();
            delLeader.setSupervisorProjectId(id);
            projectLeaderService.delete(delLeader);
            ProjectBcUnit projectBcUnit = new ProjectBcUnit();
            projectBcUnit.setProjectId(id);
            projectBcUnitService.delete(projectBcUnit);
            //删除admin
            ProjectAdmin admin = new ProjectAdmin();
            admin.setSpId(id);
            projectAdminService.delete(admin);
            //删除package:
            ProjectContract contract = new ProjectContract();
            contract.setProjectId(id);
            projectContractService.delete(contract);
            //删除阶段:
            JcProjectStage stage = new JcProjectStage();
            stage.setProjectId(id);
            jcProjectStageService.delete(stage);
            //删除里程
            JcProjectMilepost milepost = new JcProjectMilepost();
            milepost.setProjectId(id);
            jcProjectMilepostService.delete(milepost);
            //删除pay:
            JcProjectPay pay = new JcProjectPay();
            pay.setSppPrjid(id);
            jcProjectPayService.delete(pay);
            //删除file:
            SupervisorFile projectFile = new SupervisorFile();
            projectFile.setProjectId(id);
            List<SupervisorFile> select = jcFileService.select(projectFile);
            for (SupervisorFile file : select) {
                String url = file.getUrl();
                if (StringUtils.isNotBlank(url)) {
                    File delFile = new File(url);
                    delFile.delete();
                }
            }
            jcFileService.delete(projectFile);
            jcProjectService.deleteByPrimaryKey(id);
        } else {
            //跑路了
        }
    }

    /**
     * @param request
     * @Author:Zhangshuo
     * @Description:修改项目基本信息
     * @Date:9:46 2020-12-12
     */
    @GetMapping(value = "projectInfor")
    public String projectInfo(HttpServletRequest request, Model model) {
        String id = request.getParameter("id");

        // 查询项目
        JcProjectDTO jcProjectdto = new JcProjectDTO();
        jcProjectdto.setId(id);
        List<JcProjectDTO> projectlist = jcProjectService.selectSupervisorProject(jcProjectdto);
        if (projectlist.size() > 0) {
            jcProjectdto = projectlist.get(0);
        }

        //供需表Id
        String supProjectId = jcProjectdto.getSupProjectId();
        if (StringUtil.isNotBlank(supProjectId)) {
            SupplierProject project = supplierProjectManagerService.selectByPrimaryKey(supProjectId);
            String contractNo = project.getContractNo();
            String payOrProjectNo = project.getPayOrProjectNo();
            String checkShape = project.getCheckShape();

            if (StringUtil.isNotBlank(contractNo)) {
                request.setAttribute("htbh", "0");
            }
            if (StringUtil.isNotBlank(payOrProjectNo)) {
                request.setAttribute("cgbh", "0");
            }
            if (StringUtil.isNotBlank(checkShape)) {
                request.setAttribute("jlxs", "0");
            }

        }

        /*项目负责人*/
        ProjectLeaderDTO leader = new ProjectLeaderDTO();
        leader.setSupervisorProjectId(id);
        List<ProjectLeaderDTO> listyz = projectLeaderService.selectProjectLeaderList(leader);
        List<ProjectBcUnit> listbc = projectBcUnitService.queryListByPro(id);
        // 查询项目阶段 不包含其他监理工作
        JcProjectStageDTO dto = new JcProjectStageDTO();
        dto.setProjectId(id);
        dto.setNotStageNo("005");
        List<JcProjectStageDTO> listStage = jcProjectStageService.selectProjectStage(dto);
        // 查询项目里程
        JcProjectMilepostDTO su = new JcProjectMilepostDTO();
        su.setProjectId(id);
        List<JcProjectMilepostDTO> AlistMilePost = jcProjectMilepostService.selectProjectmilepost(su);
        /*项目来源*/
        List<BaseDict> projectSourcelist = DictUtil.getDictByType(DictTypes.PROJECT_SOURCE);
        /*项目类型*/
        List<BaseDict> projectTypeList = DictUtil.getDictByType(DictTypes.PROJECT_TYPEJC);
        /*监理形式*/
        List<BaseDict> checkShapeList = DictUtil.getDictByType(DictTypes.CHECK_SHAPE);
        /*是否续签*/
        List<BaseDict> isContinueList = DictUtil.getDictByType(DictTypes.IS_CONTINUE);
        /*行业类型*/
        List<BaseDict> AlstHyType = DictUtil.getDictByType(DictTypes.INDUSTRY);
        /*项目归属*/
        List<BaseCompany> AlstCompany = baseCompanyService.selectAll();

        // 项目归属
        List<BaseCompanyOwner> alstCompanyGs = baseCompanyOwnerService.selectAll();
        /*技术负责人*/
        SysUserDTO sysUser = new SysUserDTO();
        sysUser.setCompanyName(jcProjectdto.getSupervisorCompany());
        sysUser.setUserRole("jcjsfzr");
        List<SysUser> Alsttelplist = sysUserService.getUserDicts(sysUser);
        /*咨询单位行业负责人*/
        sysUser.setUserRole("sqqzr");
        List<SysUser> sqqzrlist = sysUserService.getUserDicts(sysUser);
        /*项目经理*/
        sysUser.setUserRole("jcxmjl");
        List<SysUser> Alstpmplist = sysUserService.getUserDicts(sysUser);
        /*咨询顾问*/
        sysUser.setUserRole("jcgw");
        List<SysUser> jcAdviser = sysUserService.getUserDicts(sysUser);
        // 省
        List<SysRegion> provincelist = sysRegionService.selectListByLevelId("1");
        // 市
        List<SysRegion> citylist = sysRegionService.selectSysRegionByParentCode(jcProjectdto.getProvince());
        // 县
        List<SysRegion> countylist = sysRegionService.selectSysRegionByParentCode(jcProjectdto.getCity());
        List<BaseDict> ywList = baseDictService.selectYw(jcProjectdto.getProjectType());
        //获取监理合同额----监理实施细则里程碑显示阈值
        List<BaseDict> supervisorContractQuota = DictUtil.getDictByType(DictTypes.JLHTE);
        /*判断当前角色 总监理工程师只能修改 总工期和阶段时长 */
        String jsfzr = "";
        String superEn = jcProjectdto.getTechnologyPerson();
        String userId = CommonUtil.getUserId();
        if (userId.equals(superEn)) {
            if (jcProjectdto.getStatus() != "001" && jcProjectdto.getStatus() != "003") {
                jsfzr = "true";
            } else {
                jsfzr = "false";
            }
        } else {
            jsfzr = "false";
        }
        String createrId = jcProjectdto.getCreateBy();
        SysUser creater = sysUserService.selectByPrimaryKey(createrId);
        if (creater != null && StringUtils.isNotBlank(creater.getSource()) && "001".equals(creater.getSource())) {
            request.setAttribute("createrzz", "1");
        }
        String xmjl = jcProjectdto.getProjectManagerPerson();
        if (CommonUtil.getUserId().equals(xmjl)) {
            request.setAttribute("xmjl", "1");
        } else {
            request.setAttribute("xmjl", "0");
        }

        ProjectPlaceDTO pacedto = new ProjectPlaceDTO();
        pacedto.setSupProjectId(jcProjectdto.getId());
        pacedto.setType("001");
        List<ProjectPlaceDTO> listpalce = projectPlaceService.selectPlace(pacedto);
        for (int i = 0; i < listpalce.size(); i++) {
            String province = listpalce.get(i).getProvince();
            List<SysRegion> citylist1 = sysRegionService.selectSysRegionByParentCode(province);
            listpalce.get(i).setCitys(citylist1);
            String city = listpalce.get(i).getCity();
            List<SysRegion> countylist2 = sysRegionService.selectSysRegionByParentCode(city);
            listpalce.get(i).setCountys(countylist2);
        }
        jcProjectdto.setProjectPlacedtos(listpalce);
        if (listpalce.size() == 0) {
            ProjectPlaceDTO p = new ProjectPlaceDTO();
            listpalce.add(p);
        }
        model.addAttribute("listpalce", listpalce);
        request.setAttribute("ywList", ywList);
        request.setAttribute("prj", jcProjectdto);
        request.setAttribute("listyz", listyz);
        request.setAttribute("listbc", listbc);
        request.setAttribute("projectTypeList", projectTypeList);
        request.setAttribute("provincelist", provincelist);
        request.setAttribute("citylist", citylist);
        request.setAttribute("countylist", countylist);
        request.setAttribute("listStage", listStage);
        request.setAttribute("listMilePost", AlistMilePost);
        request.setAttribute("projectSourcelist", projectSourcelist);
        request.setAttribute("checkShapeList", checkShapeList);
        request.setAttribute("isContinueList", isContinueList);
        request.setAttribute("hytypelist", AlstHyType);
        request.setAttribute("comlist", AlstCompany);
        model.addAttribute("comlistOwner", alstCompanyGs);
        request.setAttribute("telplist", Alsttelplist);
        request.setAttribute("suerlist", sqqzrlist);
        request.setAttribute("jcAdviser", jcAdviser);
        request.setAttribute("pmplist", Alstpmplist);
        request.setAttribute("supervisorContractQuota", supervisorContractQuota.size() > 0 ? supervisorContractQuota.get(0).getBadtLevel1() : "");
        request.setAttribute("jlssxzMilepost", "007");
        request.setAttribute("jlssxzMilepost2", "016");
        request.setAttribute("jsfzr", jsfzr);
        return "/jc/create/projectInfo";
    }

    /*
     * @Author:mr.hanchen
     * @Description:保存基本信息
     * @param jcProjectDTO
     * @Date:10:50 2021/6/30
     */
    @RequestMapping("/createupdate")
    @ResponseBody
    public JsonUtil saveProcject(JcProjectDTO jcProjectDTO) {
        TrimUtil.trimBean(jcProjectDTO);
        String state = jcProjectDTO.getStatus();
        // 创建项目
        if (jcProjectDTO != null) {
            try {
                //获取老值
                JcProjectDTO oldProjectInfo = new JcProjectDTO();
                oldProjectInfo.setId(jcProjectDTO.getId());
                oldProjectInfo = jcProjectService.getOldProjectInfo(oldProjectInfo);
                if (!"001".equals(oldProjectInfo.getStatus())) {
                    //比较并修改记录留痕
                    jcProjectService.compareProject(oldProjectInfo, jcProjectDTO, CommonUtil.getUserId());
                }
                if (!"002".equals(jcProjectDTO.getStatus())) {
                    jcProjectDTO.setStatus(oldProjectInfo.getStatus());
                }

                // 项目表
                JcProject jcProject = new JcProject();
                BeanUtil.copyNotNullBean(jcProjectDTO, jcProject);
                jcProject.setProjectName(jcProject.getProjectName().trim());
                jcProjectDTO.setProjectName(jcProject.getProjectName().trim());
                String status = jcProjectDTO.getStatus();
                if ("002".equals(status)) {
                    //记录提交时间
                    jcProject.setCommitBy(CommonUtil.getUserId());
                    jcProject.setCommitDate(DateUtil.getCurrentDateString());
                }
                /*校验项目名称是重复*/
//                Example e = new Example(JcProject.class);
//                Example.Criteria c = e.createCriteria();
//                c.andNotEqualTo("id", jcProjectDTO.getId());
//                c.andEqualTo("projectName", jcProjectDTO.getProjectName());
//                int count = jcProjectService.selectCountByExample(e);

                Example e = new Example(JcProject.class);
                Example.Criteria c = e.createCriteria();
                c.andNotEqualTo("id", jcProjectDTO.getId());
                c.andEqualTo("projectName", jcProjectDTO.getProjectName());
                List<JcProject> selectcount = jcProjectService.selectByExample(e);
                if (selectcount != null) {
                    if (selectcount.size() > 0) {
                        String createBy = selectcount.get(0).getCreateBy();
                        SysUser sysUser = sysUserService.selectByPrimaryKey(createBy);
                        String realName = sysUser.getRealName();
                        return JsonUtil.error("修改项目失败:项目名称重复！该项目已经被项目经理" + realName + "创建");
                    }

                }
                // 插入项目主表数据
                boolean AbFlag = jcProjectService.updateByPrimaryKeySelective(jcProject) > 0;
                jcProjectDTO.setProjectId(jcProject.getId());
                if (AbFlag) {
                    // 分包数据
                    savePackage(jcProjectDTO);
                    // 项目负责人
                    saveLeader(jcProjectDTO);
                    saveBcUnit(jcProjectDTO);
                    // 阶段数据和里程数据
                    saveStage(jcProjectDTO, true);
                    // 付款方式
                    savePayWays(jcProjectDTO);
                    jcProjectService.resetProgress(jcProjectDTO.getProjectId());
                    //保存 地点
                    ProjectPlace placeDTO = new ProjectPlace();
                    placeDTO.setSupProjectId(jcProjectDTO.getId());
                    placeDTO.setType("001");
                    projectPlaceService.delete(placeDTO);
                    //（2） 保存合同签订地点
                    jcProjectService.addPalce(jcProjectDTO);
                    if ("002".equals(state)) {
                        // 管理员账号
                        saveAdmin(jcProjectDTO);
                        JcProjectMilepost milepostnew = new JcProjectMilepost();
                        milepostnew.setProjectId(jcProjectDTO.getProjectId());
                        List<JcProjectMilepost> milepostcurr = jcProjectMilepostService.select(milepostnew);
                        for (int x = 0; x < milepostcurr.size(); x++) {
                            saveSpecialMilePost(jcProjectDTO, milepostcurr.get(x));
                        }
                    }
                }

                if ("002".equals(state)) {
                    JsonUtil ss = JsonUtil.sucess("提交项目成功");
                    return ss;
                } else {
                    JsonUtil ss = JsonUtil.sucess("修改项目成功");
                    return ss;
                }
            } catch (Exception e) {
                e.printStackTrace();
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                return JsonUtil.error("修改项目失败:" + e.getMessage());
            }
        } else {
            return JsonUtil.error("用户验证失败！！");
        }
    }

    @ResponseBody
    @GetMapping(value = "/getlistbyprjid")
    public ReType getPaysByProjectId(JcProjectPay jcProjectPay) {
        ReType re = new ReType();
        try {
            JcProjectPayDTO dto = new JcProjectPayDTO();
            dto.setSppPrjid(jcProjectPay.getSppPrjid());
            List<JcProjectPayDTO> AlistData = jcProjectPayService.selectSupervisorProjectPay(dto);
            re.setCode(0);
            re.setData(AlistData);
        } catch (Exception e) {
            e.printStackTrace();
            re.setCode(500);
            re.setMsg("根据项目编号获取付款方式异常！！" + e.getMessage());
        }
        return re;
    }

    /**
     * @param jcProjectDTO
     * @Author:Zhangshuo
     * @Description: 里程特殊处理
     * @Date:12:39 2020-12-09
     */
    public void saveSpecialMilePost(JcProjectDTO jcProjectDTO, JcProjectMilepost jcProjectMilepost) throws Exception {
        String supProjectId = jcProjectDTO.getSupProjectId();
        switch (jcProjectMilepost.getMilepostNo()) {

            case "001"://招投标文件

                if (StringUtil.isNotBlank(supProjectId)) {
                    // 招标文件
                    saveContractCompare(jcProjectDTO, jcProjectMilepost, "001", ".docx", "1");
                    //投标文件
                    saveContractCompare(jcProjectDTO, jcProjectMilepost, "002", ".docx", "2");
                }

                break;
            case "002":
                if (StringUtil.isNotBlank(supProjectId)) {
                    //合同
                    saveContractCompare(jcProjectDTO, jcProjectMilepost, "003", ".docx", "9");
                }
                break;
            default:
                break;
        }
    }

    /**
     * @param jcProjectDTO
     * @param jcProjectMilepost
     * @Author:Zhangshuo
     * @Description:
     * @Date:12:38 2020-12-09
     */
    public void saveContractCompare(JcProjectDTO jcProjectDTO, JcProjectMilepost jcProjectMilepost, String AsFileType, String AsFileStuffix, String AsFileConfigId) throws Exception {
        String milepost = jcProjectMilepost.getMilepostNo();
        String AsTemplateFile = FilePathUtil.getPathConfigTemplateFile(AsFileConfigId);
        if ("001".equals(milepost)) {
            // 查询招标文件
            //上传项目招标文件说明文件  311
            //上传项目招标文件  312
            //上传项目投标文件  313
            //上传合同  314
            //上传合同说明文件  315

            // 招标文件处理
            if ("001".equals(AsFileType)) {
                updateCopyGxZbFile(jcProjectDTO, AsFileConfigId, jcProjectMilepost, AsFileType, AsFileStuffix);
            } else if ("002".equals(AsFileType)) {
                // 投标文件
                updateCopyGxTbFile(jcProjectDTO, AsFileConfigId, jcProjectMilepost, AsFileType, AsFileStuffix);
            }

        } else if ("002".equals(milepost)) {
            //上传合同  314
            //上传合同说明文件  315
            // 合同
            if ("003".equals(AsFileType)) {
                // 合同
                updateCopyGxhTFile(jcProjectDTO, AsFileConfigId, jcProjectMilepost, AsFileType, AsFileStuffix);
            }

        } else if ("033".equals(milepost)) {
            /*变更处理*/
            SupervisorFile supervisorFile = new SupervisorFile();
            supervisorFile.setProjectId(jcProjectDTO.getProjectId());
            supervisorFile.setStageId(jcProjectMilepost.getSupervisorProjectStageId());
            supervisorFile.setSpmId(jcProjectMilepost.getId());
            supervisorFile.setType(AsFileType);
            int AiFile = supervisorFileService.selectCount(supervisorFile);
            if (AiFile == 0) {
                UploadType uploadType = UploadType.getEnumByType(0);
                uploadType.setFilePathId(AsFileConfigId);
                String pNo = "001";
                String AsFileName = FileUtils.getFileNameByNoJc(jcProjectDTO.getProjectName(), AsFileType, "", AsFileStuffix, pNo);
                uploadType.setFileName(AsFileName);
                List<String> AlstPlaceHolder = new ArrayList<>();
                AlstPlaceHolder.add(jcProjectDTO.getProjectName());
                uploadType.setPlaceholder(AlstPlaceHolder);
                String AsFilePath = FilePathUtil.getFullSavePathAndNameByConfigFileId(uploadType);
                supervisorFile.setUrl(AsFilePath);
                supervisorFile.setFileName(AsFileName);
                supervisorFile.setInd(1);
                supervisorFile.setFileType(FilePathUtil.getFileSufiix(AsFileName));
                try {
                    if (FileUtils.CopyFile(AsTemplateFile, AsFilePath)) {
                        supervisorFileService.insertSelective(supervisorFile);
                    }
//                else {
//
//                        throw new Exception("复制PathConfig中TemplateFile出现异常");
//                }
                } catch (Exception e) {
                    e.printStackTrace();
                }

            }

        } else {
            /**/
            ArrayList<ProjectContract> projectContractList = jcProjectDTO.getProjectContracts();
            if (projectContractList == null) {
                return;
            }
            /*获取承建单位*/
            ArrayList<ProjectUnitConstructionDTO> unitConstructionList = jcProjectDTO.getProjectUnitConstructions();
            if (unitConstructionList == null) {
                return;
            }
            int AiCnt = projectContractList.size();
            /**/
            int k = 0;
            for (int i = 0; i < AiCnt; i++) {

                for (int j = 0; j < unitConstructionList.size(); j++) {
                    /*承建分包编号*/
                    String cjFbCode = unitConstructionList.get(j).getConstructionSubContractNumber();
                    ProjectContract projectContract = projectContractList.get(i);
                    /*分包编号*/
                    String AsFbCode = projectContract.getCode();
                    if (StringUtil.isNotBlank(AsFbCode)) {
                        if (AsFbCode.equals(cjFbCode)) {
                            /*存在承建单位的分包才 生成模板*/
                            SupervisorFile supervisorFile = new SupervisorFile();
                            supervisorFile.setProjectId(jcProjectDTO.getProjectId());
                            supervisorFile.setPcId(projectContract.getId());
                            supervisorFile.setStageId(jcProjectMilepost.getSupervisorProjectStageId());
                            supervisorFile.setSpmId(jcProjectMilepost.getId());
                            supervisorFile.setType(AsFileType);
                            int AiFileCnt = supervisorFileService.selectCount(supervisorFile);
                            if (AiFileCnt == 0) {
                                UploadType uploadType = UploadType.getEnumByType(0);
                                uploadType.setFilePathId(AsFileConfigId);
                                String pNo = "001";
                                if ("20".equals(AsFileConfigId) || "23".equals(AsFileConfigId)) {
                                    pNo = StringUtil.autoGenericCode((k + 1) + "", 3);
                                }
                                String AsFileName = FileUtils.getFileNameByNoJc(jcProjectDTO.getProjectName(), AsFileType, AsFbCode, AsFileStuffix, pNo);
                                uploadType.setFileName(AsFileName);
                                List<String> AlstPlaceHolder = new ArrayList<>();
                                AlstPlaceHolder.add(jcProjectDTO.getProjectName());
                                AlstPlaceHolder.add(AsFbCode);
                                uploadType.setPlaceholder(AlstPlaceHolder);

                                String AsFilePath = FilePathUtil.getFullSavePathAndNameByConfigFileId(uploadType);
                                supervisorFile.setUrl(AsFilePath);
                                supervisorFile.setFileName(AsFileName);
                                supervisorFile.setInd((k + 1));
                                supervisorFile.setFileType(FilePathUtil.getFileSufiix(AsFileName));
                                if (FileUtils.CopyFile(AsTemplateFile, AsFilePath)) {
                                    supervisorFileService.insertSelective(supervisorFile);
                                    if ("20".equals(AsFileConfigId) || "23".equals(AsFileConfigId)) {
                                        //动态更改文件的包号
                                        Map<String, String> bookmarkMap = new HashMap<>();
                                        /*项目名称*/
                                        bookmarkMap.put("PO_F1", jcProjectDTO.getProjectName());
                                        /*业主单位*/
                                        bookmarkMap.put("PO_F2", jcProjectDTO.getOwerCompany());
                                        String superCompanyId = jcProjectDTO.getSupervisorCompany();
                                        BaseCompany baseCompany = baseCompanyService.selectByPrimaryKey(superCompanyId);
                                        if (baseCompany != null) {
                                            /*监理单位*/
                                            bookmarkMap.put("PO_F3", baseCompany.getBcName());
                                        }
                                        /*承建单位*/
                                        bookmarkMap.put("PO_F4", unitConstructionList.get(j).getUnitConstruction());
                                        bookmarkMap.put("PO_C", pNo);
                                        WordUtil.replaceBookmark(AsFilePath, AsFilePath, bookmarkMap);
                                    }
                                } else {
                                    throw new Exception("复制PathConfig中TemplateFile出现异常");
                                }
                            }
                            k++;
                        }
                    }
                }
            }
        }


    }
}
